﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace GPforRobocode
{
    static class Read
    {
        static public Solution ReadString(string str)
        {
            //string str = "Mul(Firing(Y)Abs(EnemyEnergy))";
            int index,index2;
            List<NTree<string>> STACK = new List<NTree<string>>();
            NTree<string> tree;
            NTree<string> node;
            NTree<string> FaterTree;
            while(str.Length > 0){
                index = str.IndexOf('(');
                index2 = str.IndexOf(')');
                if (index < index2 && index!=-1)
                {
                    string A = str.Substring(0, index);
                    tree = new NTree<string>(A);
                    STACK.Add(tree);
                    tree = new NTree<string>("(");
                    STACK.Add(tree);
                    str = str.Substring(index + 1);
                }
                else {
                    string A = str.Substring(0, index2);
                    node = new NTree<string>(A);
                    tree = STACK[STACK.Count-1];
                    STACK.RemoveAt(STACK.Count-1);
                    if (tree.Data == "(")
                    {
                        tree = STACK[STACK.Count-1];
                        tree.addChild(node);
                        str = str.Substring(index2 + 1);
                    }
                    else {
                        int index3 = STACK.FindLastIndex(delegate(NTree<string> Tree) { return Tree.Data == "("; });
                        FaterTree = STACK[index3 - 1];
                        for (int i = index3; i < STACK.Count; i++) {
                            if (STACK[i].Data != "(" && STACK[i].Data != ")") {
                                FaterTree.addChild(STACK[i]);
                            }
                        }
                        FaterTree.addChild(tree);
                       // FaterTree.addChild(node);
                        STACK.RemoveRange(index3, STACK.Count - index3);
                        str = str.Substring(index2 + 1);
                    }
                }
            }
              Solution ret = new Solution(STACK[0]);
              return ret;
        }
      
    }
}

